<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>YOLOv5 Object Detection</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1280px;
            margin: 0 auto;
            text-align: center;
        }
        h1 {
            color: #333;
            margin-bottom: 20px;
        }
        .image-section, .video-section {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-top: 20px;
        }
        .image-title, .video-title {
            margin: 0 0 5px 0;
            color: #333;
            font-weight: bold;
            text-align: center;
        }
        .image-box {
            width: 480px;
            height: 270px;
            background-color: #fff;
            border: 1px solid #ddd;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            overflow: hidden;
            position: relative;
            cursor: pointer;
        }
        .image-box img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 5px;
            transition: transform 0.2s;
        }
        .image-box img:hover {
            transform: scale(1.05);
        }
        .video-box {
            width: 480px;
            height: 270px;
            background-color: #fff;
            border: 1px solid #ddd;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            overflow: hidden;
            position: relative;
        }
        .video-box img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 5px;
        }
        .form-section {
            margin: 20px 0;
        }
        button {
            padding: 10px 20px;
            margin: 5px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }
        button:hover {
            background-color: #0056b3;
        }
        .flash-message {
            color: red;
            margin: 10px 0;
        }
        #videoContainer {
            display: none;
            margin-top: 20px;
            text-align: center;
        }
        #video {
            width: 1000px;
            height: 800px;
            max-width: 100%;
            height: auto;
            object-fit: contain;
        }
        @media (max-width: 1280px) {
            #video {
                width: 100%;
                height: auto;
            }
            .video-box {
                width: 100%;
                max-width: 480px;
                height: 270px;
            }
        }
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.8);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }
        .modal-content {
            max-width: 90%;
            max-height: 90%;
            object-fit: contain;
            border-radius: 5px;
        }
        .close {
            position: absolute;
            top: 20px;
            right: 20px;
            color: white;
            font-size: 30px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>YOLOv5 Object Detection</h1>

        {% with messages = get_flashed_messages(with_categories=true) %}
            {% if messages %}
                {% for category, message in messages %}
                    <p class="flash-message" style="color: {{ 'red' if category == 'error' else 'green' }}">{{ message }}</p>
                {% endfor %}
            {% endif %}
        {% endwith %}

        <!-- 图片检测 -->
        <div class="form-section">
            <form id="uploadForm" method="POST" enctype="multipart/form-data">
                <input type="file" name="file" id="fileInput" accept="image/*" onchange="previewImage()" style="display: none;">
                <button type="button" onclick="document.getElementById('fileInput').click()">Choose Image</button>
                <button type="submit">Detect Image</button>
            </form>
        </div>

        <div class="image-section">
            <div>
                <p class="image-title">Original Image</p>
                <div class="image-box" onclick="openModal('originalImage')">
                    <img id="originalImage" src="/static/back.jpg" alt="Original Image">
                </div>
            </div>
            <div>
                <p class="image-title">Detection Result</p>
                <div class="image-box" onclick="openModal('resultImage')">
                    <img id="resultImage" src="{% if detection_done %}/static/img.jpg{% else %}/static/back.jpg{% endif %}" alt="Detection Result">
                </div>
            </div>
        </div>

        <!-- 视频检测 -->
        <h2>Video Detection</h2>
        <div class="form-section">
            <form id="uploadVideoForm" method="POST" enctype="multipart/form-data" action="/upload_video">
                <input type="file" name="video" id="videoInput" accept="video/*" style="display: none;" onchange="uploadVideo()">
                <button type="button" onclick="document.getElementById('videoInput').click()">Choose Video</button>
                <button type="submit" id="uploadButton" style="display: none;">Upload Video</button>
            </form>
            <button onclick="startVideoDetection()" id="startDetectionButton" style="display: none;">Start Detection</button>
            <button onclick="stopVideoFeed()" id="stopDetectionButton" style="display: none;">Stop Detection</button>
        </div>
        <div class="video-section" id="videoSection" style="display: none;">
            <div>
                <p class="video-title">Original Video</p>
                <div class="video-box">
                    <img id="originalVideoFeed" src="" alt="Original Video Feed">
                </div>
            </div>
            <div>
                <p class="video-title">Detection Result</p>
                <div class="video-box">
                    <img id="processedVideoFeed" src="" alt="Processed Video Feed">
                </div>
            </div>
        </div>

        <!-- 摄像头检测 -->
        <h2>Live Video Detection</h2>
        <button onclick="startVideo()">Start Video</button>
        <button onclick="stopVideo()">Stop Video</button>
        <div id="videoContainer">
            <img src="" id="video" alt="Video Feed">
        </div>

        <!-- 模态窗口 -->
        <div id="modal" class="modal">
            <span class="close" onclick="closeModal()">×</span>
            <img id="modalImage" class="modal-content" alt="Enlarged Image">
        </div>
    </div>

<script>
    function previewImage() {
        const fileInput = document.getElementById('fileInput');
        const originalImage = document.getElementById('originalImage');
        const file = fileInput.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                originalImage.src = e.target.result;
            };
            reader.readAsDataURL(file);
        }
    }

    function startVideo() {
        const video = document.getElementById('video');
        video.src = '/video_feed?' + new Date().getTime();
        document.getElementById('videoContainer').style.display = 'block';
    }

    function stopVideo() {
        const video = document.getElementById('video');
        video.src = '';
        document.getElementById('videoContainer').style.display = 'none';
        fetch('/stop_video')
            .then(response => console.log('摄像头已停止'))
            .catch(error => console.error('停止视频失败:', error));
    }

    function openModal(imageId) {
        const modal = document.getElementById('modal');
        const modalImage = document.getElementById('modalImage');
        const image = document.getElementById(imageId);
        modalImage.src = image.src;
        modal.style.display = 'flex';
    }

    function closeModal() {
        const modal = document.getElementById('modal');
        modal.style.display = 'none';
    }

    window.onclick = function(event) {
        const modal = document.getElementById('modal');
        if (event.target == modal) {
            modal.style.display = 'none';
        }
    }

    function uploadVideo() {
        const videoInput = document.getElementById('videoInput');
        const file = videoInput.files[0];
        if (file) {
            document.getElementById('uploadButton').click();
        }
    }

    function startVideoDetection() {
        const processedVideo = document.getElementById('processedVideoFeed');
        const originalVideo = document.getElementById('originalVideoFeed');
        document.getElementById('videoSection').style.display = 'flex';

        // 同步加载并播放两个视频流
        const originalSrc = '/original_video_feed?' + new Date().getTime();
        const processedSrc = '/processed_video_feed?' + new Date().getTime();
        originalVideo.src = originalSrc;
        processedVideo.src = processedSrc;

        // 添加错误处理
        originalVideo.onerror = () => {
            console.error("Failed to load original video feed");
            alert("无法加载原始视频流，请检查后端服务或视频文件");
        };
        processedVideo.onerror = () => {
            console.error("Failed to load processed video feed");
            alert("无法加载检测后的视频流，请检查后端服务或视频文件");
        };

        document.getElementById('stopDetectionButton').style.display = 'inline-block';
        console.log("Video detection started, original src:", originalSrc, "processed src:", processedSrc);
    }

    function stopVideoFeed() {
        const processedVideo = document.getElementById('processedVideoFeed');
        const originalVideo = document.getElementById('originalVideoFeed');
        // 清除 onerror 事件，避免弹窗
        originalVideo.onerror = null;
        processedVideo.onerror = null;
        // 清空 src 并隐藏
        originalVideo.src = '';
        processedVideo.src = '';
        document.getElementById('videoSection').style.display = 'none';
        document.getElementById('startDetectionButton').style.display = 'none';
        document.getElementById('stopDetectionButton').style.display = 'none';
    }

    window.onload = function() {
        const messages = document.getElementsByClassName('flash-message');
        for (let msg of messages) {
            console.log("Message:", msg.textContent);
            if (msg.textContent.includes('视频上传成功')) {
                console.log("Video upload success detected");
                document.getElementById('videoSection').style.display = 'flex';
                document.getElementById('startDetectionButton').style.display = 'inline-block';
                const originalVideo = document.getElementById('originalVideoFeed');
                // 加载视频第一帧作为预览
                originalVideo.src = '/video_first_frame?' + new Date().getTime();
            }
        }
    }
</script>
</body>
</html>